<template>
  <view class="warp">
    <view></view>
    <ff-partner backgroud="#55aaff" :participants="ppts"></ff-partner>
    <view></view>
    <ff-partner backgroud="#55aaff" :participants="ppts"></ff-partner>
    <view style="text-align: center; width: 100%">{{ ppts.length }}个</view>
    <ff-partner backgroud="#55aa7f" :participants="ppts"></ff-partner>
    <view style="text-align: center; width: 100%">
      {{ participants.length }}个
    </view>
    <ff-partner backgroud="#eaeaea" :participants="participants"></ff-partner>

    <!-- 添加底部安全区域占位 -->
    <view class="tabbar-placeholder"></view>
    <!-- 使用自定义 TabBar 组件 -->
    <cc-myTabbar :tabBarShow="0"></cc-myTabbar>
  </view>
</template>

<script>
import { qrcode, coach, edit_info, getUserInfo } from "../../api/fit";
import CustomTabbar from "../../components/custom-tabbar/custom-tabbar.vue";

export default {
  components: {
    CustomTabbar,
  },
  data() {
    return {
      ppts: [
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
      ],
      baseList: [
        {
          name: "photo",
          title: "图片",
        },
        {
          name: "lock",
          title: "锁头",
        },
      ],
      participants: [
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
        { gender: "男", nickname: "张三" },
      ],
      logoSrc: "",
      showModal: false,
      qrCodeUrl: "",
      role: "",
      planName: "",
      userName: "",
      coachPlan: {
        planCount: 0,
        physicalFitnessCount: 0,
      },
      dataList: [],
      unitOptions: [
        { label: "次", value: "c" },
        { label: "秒", value: "s" },
        { label: "分", value: "m" },
      ],
      avatarUrl: "",
      isEditing: false,
      // TabBar 相关数据
      currentTabIndex: 0,
      tabBarItems: [
        { icon: "🏠", text: "首页", url: "/pages/index/index" },
        { icon: "🔍", text: "分类", url: "/pages/category/index" },
        { icon: "+", text: "发布", url: "" },
        { icon: "💬", text: "消息", url: "/pages/message/index" },
        { icon: "👤", text: "我的", url: "/pages/user/index" },
      ],
    };
  },
  onShow() {
    this.getPlanDetails();
  },

  async onLoad() {
    this.role = uni.getStorageSync("role");
    await this.getUserInfo();
    // 获取二维码
    await this.getQrCode();
    // 获取role

    // 获取计划详情
  },

  onShareAppMessage(res) {
    return {
      title: "品铁计划",
      path: "/pages/index/index",
      imageUrl: "../../static/logo.jpg",
      success(res) {
        uni.showToast({
          title: "分享成功",
        });
      },
      fail(res) {
        uni.showToast({
          title: "分享失败",
          icon: "none",
        });
      },
    };
  },

  onShareTimeline() {
    return {
      title: "品铁计划",
      query: "",
      imageUrl: "../../static/logo.jpg",
    };
  },

  methods: {
    async getUserInfo() {
      try {
        const res = await getUserInfo();
        const { user, tenantEntity } = res.data;
        this.$set(
          this,
          "avatarUrl",
          user.avatar
            ? `https://api.itaster.cn/file/${user.avatar}`
            : "../../static/logo1.png"
        );
        this.$set(
          this,
          "logoSrc",
          tenantEntity.background
            ? `https://api.itaster.cn/file/${tenantEntity.background}`
            : "../../static/logo1.png"
        );
        this.userName = user.nickname;
        console.log(this.userName, "this.avatarUrl");

        console.log(this.logoSrc, "logoSrc");
      } catch (err) {
        console.error("报错了", err);
      }
    },

    saveNetImageToLocal(url) {
      uni.saveImageToPhotosAlbum({
        filePath: url,
        success: (res) => {
          uni.hideLoading();
          console.log(res, "?????????????????????????????????");
          return uni.showToast({
            title: "保存成功！",
          });
        },
        fail: (res) => {
          uni.hideLoading();
          console.log(res.errMsg);
          return uni.showToast({
            title: "保存失败，请重试！",
            icon: "none",
          });
        },
        //无论成功失败都走的回调
        complete: (res) => {
          uni.hideLoading();
        },
      });
    },
    async getQrCode() {
      try {
        const res = await qrcode();
        const token = uni.getStorageSync("token");
        const encodedToken = encodeURIComponent(`Bearer ${token}`);
        this.$set(
          this,
          "qrCodeUrl",
          `https://api.itaster.cn/api/common/qrcode?token=${encodedToken}`
        );
        console.log(this.qrCodeUrl, "qrqrqrqr");
      } catch (err) {
        console.error(err);
      }
    },

    async getPlanCount() {
      try {
        let data = {
          userId: uni.getStorageSync("role_id"),
        };
        const res = await planCount(data);
        if (res.data.length > 0) {
          this.planCount = res.data[0];
        } else {
          this.planCount = {
            planCount: 0,
            physicalFitnessCount: 0,
          };
        }
        console.log(res, "sadasdas");
      } catch (err) {}
    },

    async getPlanDetails() {
      try {
        // 获取本月第一天和最后一天
        const now = new Date();
        const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
        const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);

        // 格式化日期为 YYYY-MM-DD
        const formatDate = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0");
          const day = String(date.getDate()).padStart(2, "0");
          return `${year}-${month}-${day}`;
        };

        let data = {
          userId: uni.getStorageSync("role_id"),
          page: 1,
          size: 10,
          startTime: formatDate(firstDay),
          endTime: formatDate(lastDay),
        };

        const res = await coach(data);
        if (res.data.list.length > 0) {
          this.coachPlan = res.data.list[0];
        } else {
          this.coachPlan = {
            planCount: 0,
            physicalFitnessCount: 0,
          };
        }
        console.log(res, "sadasdas");
        this.dataList = res.data.nodes;
        this.planName = res.data.planName;
      } catch (err) {
        console.error(err);
      }
    },

    showQrCode() {
      const token = uni.getStorageSync("token");
      const encodedToken = encodeURIComponent(`Bearer ${token}`);
      this.$set(
        this,
        "qrCodeUrl",
        `https://api.itaster.cn/api/common/qrcode?token=${encodedToken}`
      );
      console.log(this.qrCodeUrl, "12312312312");

      this.showModal = true;
    },

    closeModal() {
      this.showModal = false;
    },

    goUrl(type) {
      if (type == 1) {
        uni.redirectTo({
          url: "/pages/muban/list",
        });
      } else if (type == 2) {
        uni.redirectTo({
          url: "/pages/customer/index",
        });
      } else {
        uni.redirectTo({
          url: "/pages/kecheng/customer",
        });
      }
    },

    async uploadAvatar() {
      const that = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: async function (res) {
          const tempFilePaths = res.tempFilePaths;
          // 上传图片到服务器
          const uploadRes = await uni.uploadFile({
            url: "https://api.itaster.cn/api/common/upload", // 替换为你的上传接口
            filePath: tempFilePaths[0],
            name: "file",
            header: {
              Authorization: "Bearer " + uni.getStorageSync("token"),
            },
          });
          const data = JSON.parse(uploadRes.data);
          console.log(data, "data");
          if (data.code === 200) {
            that.avatarUrl = "https://api.itaster.cn/file/" + data.message;
            // 调用修改信息的接口
            await that.updateUserInfo(data.message);
          } else {
            uni.showToast({
              title: "上传失败",
              icon: "none",
            });
          }
        },
      });
    },

    async updateUserInfo(avatarUrl) {
      try {
        const res = await edit_info({ avatar: avatarUrl });
        if (res.code === 200) {
          uni.showToast({
            title: "头像更新成功",
            icon: "success",
          });
          this.getUserInfo();
        } else {
          uni.showToast({
            title: "头像更新失败",
            icon: "none",
          });
        }
      } catch (err) {
        console.error(err);
        uni.showToast({
          title: "头像更新失败",
          icon: "none",
        });
      }
    },

    async updateNickname() {
      this.isEditing = false;
      try {
        const res = await edit_info({ nickname: this.userName });
        if (res.code === 200) {
          uni.showToast({
            title: "名称更新成功",
            icon: "success",
          });
          this.getUserInfo();
        } else {
          uni.showToast({
            title: "名称更新失败",
            icon: "none",
          });
        }
      } catch (err) {
        console.error("更新名称失败:", err);
        uni.showToast({
          title: "更新失败，请重试",
          icon: "none",
        });
      }
    },

    // TabBar 相关方法
    handleTabChange(index) {
      this.currentTabIndex = index;
    },

    handleCenterClick() {
      // 可以在这里添加额外的处理逻辑
      console.log("中间按钮被点击");
    },
  },
};
</script>

<style lang="scss">
page {
  background: #ededed;
}
.wrap {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.header {
  height: 40vh;
}

.coach-info {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  margin-top: -75rpx; /* 往上移动，覆盖部分logo */
  justify-content: space-between;
  z-index: 1;
  .coach-avatar {
    border-radius: 50%;
  }
  .coach-details {
    margin-left: 50rpx;
    .coach-name {
      font-size: 64rpx;
      font-weight: bold;
    }
  }
  .contact-service {
    margin-top: 80rpx;
    height: 30rpx;
    width: 200rpx;
    line-height: 30rpx;
    font-size: 24rpx;
    color: #fff;
    background: #000;
    white-space: inherit;
    border-radius: 20rpx;
    display: inline-block;
  }
}

.plan-info {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background: #fff;
  margin: 20rpx 0; /* 上下边距 */

  .plan-item {
    display: flex;
    align-items: flex-start;

    .plan-icon {
      margin-right: 10rpx;
    }

    .plan-details {
      .plan-title {
        font-size: 28rpx;
        color: #333;
      }

      .plan-number {
        font-size: 80rpx;
        font-weight: bold;
        color: #000;
        margin-top: 10rpx;
      }
    }
  }
}

.content {
  height: 32vh;
  padding: 60rpx 20rpx 20rpx 20rpx;
  border-radius: 40rpx;
  // border: 4rpx solid #000;
  background: #fff;
  margin-bottom: 20rpx;

  .con_detail {
  }
}

.main {
  flex: 1;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.btn {
  padding: 24rpx;
  border: 4rpx solid #000;
  border-radius: 16rpx;
  background: #000;
  color: white;
}

.invite-btn {
  padding: 24rpx;
  border: 4rpx solid #000;
  border-radius: 16rpx;
  background: white;
  color: #000;
  font-weight: bold;
  transition: all 0.3s;

  &:active {
    background: #f5f5f5;
  }
}

.qr-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;

  .modal-content {
    width: 80%;
    background: white;
    border-radius: 24rpx;
    padding: 30rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;

      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .close-btn {
        font-size: 40rpx;
        color: #999;
        padding: 8rpx;
      }
    }

    .qr-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 16rpx;

      .qr-code {
        width: 320rpx;
        height: 320rpx;
        margin-bottom: 24rpx;
      }

      .qr-tip {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

.coach-name-input {
  font-size: 32rpx;
  border: none;
  outline: none;
  width: 100%;
  background: transparent;
  color: #333;
  padding: 0;
  margin-bottom: 10rpx;

  &:focus {
    background: rgba(255, 255, 255, 0.8);
    border: none;
    outline: none;
  }
}

.user-profile {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  padding: 10px; /* 添加内边距 */
}

.avatar {
  width: 50px; /* 设置头像宽度 */
  height: 50px; /* 设置头像高度 */
  border-radius: 50%; /* 圆形头像 */
  margin-right: 10px; /* 头像与文本之间的间距 */
}

.user-info {
  display: flex;
  flex-direction: column; /* 垂直排列用户名和联系客服按钮 */
}

.username {
  margin: 0; /* 去掉默认的外边距 */
}

.contact-support {
  margin-top: 5px; /* 按钮与用户名之间的间距 */
  padding: 5px 10px; /* 按钮内边距 */
  background-color: #007bff; /* 按钮背景色 */
  color: white; /* 按钮文字颜色 */
  border: none; /* 去掉边框 */
  border-radius: 5px; /* 圆角按钮 */
  cursor: pointer; /* 鼠标悬停时显示为手型 */
}

/* 自定义底部 TabBar 样式 */
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 110rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.tabbar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 10rpx 0;
}

.tabbar-icon {
  font-size: 44rpx;
  margin-bottom: 6rpx;
  color: #8a8a8a;
}

.tabbar-text {
  font-size: 24rpx;
  color: #8a8a8a;
}

.tabbar-item.active .tabbar-icon,
.tabbar-item.active .tabbar-text {
  color: #2cc895; /* 活跃状态的颜色，与图片中的绿色按钮一致 */
}

.tabbar-center-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
  padding-bottom: 10rpx;
}

.center-icon-wrapper {
  width: 100rpx;
  height: 100rpx;
  background-color: #2cc895; /* 绿色圆形按钮 */
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6rpx;
  position: relative;
  top: -20rpx;
  box-shadow: 0 4rpx 10rpx rgba(44, 200, 149, 0.3);
}

.center-icon {
  font-size: 60rpx;
  color: #ffffff;
  font-weight: bold;
}

.tabbar-placeholder {
  height: 110rpx;
  width: 100%;
}

/* 适配 iPhone X 及以上机型底部安全区域 */
@supports (bottom: constant(safe-area-inset-bottom)) or
  (bottom: env(safe-area-inset-bottom)) {
  .custom-tabbar {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }

  .tabbar-placeholder {
    height: calc(110rpx + constant(safe-area-inset-bottom));
    height: calc(110rpx + env(safe-area-inset-bottom));
  }
}
</style>
